# coding: utf-8
from django.db import models


from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from datetime import datetime

class Poll(models.Model):
    user = models.ForeignKey(User)
    created = models.DateTimeField(u'Создание', default = datetime.now())
    title = models.CharField(u'Название', max_length = 256)
    answer_type = models.CharField(u'Ответов', choices=( ('single', u'Один'), ('multi', u'Несколько') ), default='single', max_length = 31 )
    closed = models.BooleanField(u'Закрыто', default = False)
    active = models.BooleanField(u'Активно', default = True)
    def get_url(self):
        return reverse('poll', args=(self.pk, ) )
    def __unicode__(self):
        return self.title
    @staticmethod
    def gen_vote_key():
        import random, string
        chars = string.letters+string.digits
        result = ''
        for i in range(16): result += random.choice(chars)
        return result

    class Meta:
        ordering = ['-created']

class PollVariant(models.Model):
    poll = models.ForeignKey(Poll)
    text = models.CharField(u'Текст', max_length = 512)
    votes = models.IntegerField(u'Голосов', default = 0)
    def __unicode__(self):
        return u"{0} ({1})".format(self.text, self.votes)
    class Meta:
        pass
        #unique_together = ('poll', )


class Vote(models.Model):
    poll = models.ForeignKey(Poll)
    poll_variant = models.ForeignKey(PollVariant)
    multianswer_num = models.IntegerField(u'Номер ответа', default = 0)
    key = models.CharField(u'Уник.ключ', max_length=128)
    datetime = models.DateTimeField(u'Дата', default = datetime.now() )
    def save(self):
        try:
            super(Vote, self).save()
            self.poll_variant.votes += 1
            self.poll_variant.save()
            return True
        except: return False
    class Meta:
        pass
        unique_together = ('poll', 'key', 'multianswer_num') 
